package realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("授权！");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;

        Set<String> roles = new HashSet<String>() ;
        roles.add("admin") ;
        roles.add("teach") ;

        info.setRoles(roles);

        Set<String> set1 = new HashSet<String>() ;
        set1.add("user:create") ;
        info.setStringPermissions(set1);


        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证.....");
        //得到用户名
        UsernamePasswordToken token = (UsernamePasswordToken)  authenticationToken ;
        String username = token.getUsername() ;
        SimpleAuthenticationInfo info = null ;
        if(!"admin".equals(username)){
            throw new UnknownAccountException("帐号不存在！") ;
        }
        else{
            //从数据库中得到密码
            String pwd = "123456" ;
            //
            info = new SimpleAuthenticationInfo(username,pwd,"xx") ;

        }


        return info;
    }
}
